<template>
  <div class="xinxi">
    <img class="top" src="../assets/images/message/top.png" alt="">
    <div class="bot">
      <el-form label-position="left" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">

        <div class="form one">
          <img src="../assets/images/message/年龄icon.png" alt="">
          <el-form-item class="itemform " label="年龄" prop="age">
            <!-- <el-input-number v-model="ruleForm.age" @change="handleChange" :min="1" :max="100"
              label="请输入年龄"></el-input-number> -->
            <el-input v-model="ruleForm.age" disabled placeholder="请输入年龄" maxlength="2"></el-input>
          </el-form-item>
        </div>
        <div class="form">
          <img style="width: 13px;height: 19px;" src="../assets/images/message/城市icon.png" alt="">
          <el-form-item class="itemform" label="城市" prop="city">
            <!-- <el-select style="width: 100%;" v-model="ruleForm.city" placeholder="请选择所在城市">
            <el-option label="1" value="0"></el-option>
          </el-select> -->
          <div class="sex">
            <van-field readonly clickable name="area" :value="city" placeholder="请选择城市" @click="showArea = true"
              input-align="right" />
            <van-popup v-model="showArea" position="bottom">
              <van-area title="请选择您的城市" confirm-button-text="完成" :area-list="areaList" @confirm="onCity"
                @cancel="showArea = false" />
            </van-popup>
            <img src="../assets/images/message/jt.png" alt="">
          </div>
            
          </el-form-item>
        </div>
        <div class="form">
          <img style="width: 22px;height: 18px;" src="../assets/images/message/教育icon.png" alt="">
          <el-form-item class="itemform" label="教育程度" prop="education">
            <!-- <el-select style="width: 100%;" v-model="ruleForm.education" placeholder="请选择教育程度">
            <el-option label="小学及以下" value="0"></el-option>
            <el-option label="初中" value="2"></el-option>
            <el-option label="高中" value="3"></el-option>
            <el-option label="大专" value="4"></el-option>
            <el-option label="本科" value="5"></el-option>
            <el-option label="硕士" value="6"></el-option>
            <el-option label="博士" value="7"></el-option>
          </el-select> -->
          <div class="sex">
            <van-field readonly clickable name="picker" :value="education" placeholder="请选择教育程度"
              @click="showPicker2 = true" input-align="right" />
            <van-popup v-model="showPicker2" position="bottom">
              <van-picker title="请选择您的教育程度" confirm-button-text="完成" show-toolbar :columns="type" value-key="itemText" @confirm="onEdu"
                @cancel="showPicker2 = false" />
            </van-popup>
            <img src="../assets/images/message/jt.png" alt="">
          </div>
            
          </el-form-item>
        </div>

        <div class="text"> 您的数据会脱敏处理，我们将保护您的隐私安全 </div>


      </el-form>
    </div>
    <div class="txk" v-show="show">
      <img src="../assets/images/message/packet-silver.png" alt="">
    </div>
    <div class="txk" v-show="!show" @click="submitForm('ruleForm')">
      <img src="../assets/images/message/packet.png" alt="">
    </div>
    <div class="but" @click="submitForm('ruleForm')">
      <img src="../assets/images/message/toearn.png" alt="">
    </div>

  </div>
</template>
<script>
import axios from "axios";
import api from "@/api";
import Cookies from 'js-cookie'
import config from "../config/index.js";
import { areaList } from '@vant/area-data';
import { info, submit, userinfo2 ,addpacketstep,addburyingpoint} from '@/api/http.js'
import {
  getUrl
} from "@/config.js";
import { Toast } from "vant";

export default {
  props: {

  },
  data() {
    return {
      data: {},
      imgUrl: "",
      cityIndex: "",
      eduIndex: '',
      city: "",
      mechanismMemberUserId: "",
      phone: '',
      areaList,
      showArea: false,
      showPicker2: false,
      education: '',
      userName: '',
      sex: '',
      userCardId: '',
      show:true,
      type: [
        {
          id:0,
          itemText:'小学及以下',
        },
        {
          id:2,
          itemText:'初中',
        },
        {
          id:3,
          itemText:'高中',
        },
        {
          id:4,
          itemText:'大专',
        },
        {
          id:5,
          itemText:'本科',
        },
        {
          id:6,
          itemText:'硕士',
        },
        {
          id:7,
          itemText:'博士',
        }],
      ruleForm: {
        
        age: '',
        education: '',
        delivery: false,
        type: [{}],
        
        desc: '',

      },
      rules: {
        userName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { validator: this.validateSpecial, trigger: 'blur' }
          // { required: true, message: '请输入姓名', trigger: 'blur' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        userCardId: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          { validator: this.idcard, trigger: "blur" },

        ],
        birthday: [{ required: true, message: '请输入身份证自动获取出生日期', trigger: ['change'] }],
        // education: [{ required: true, message: '请选择教育程度', trigger: 'blur' }],
        // age: [{ required: true, message: "请输入年龄", trigger: 'blur' }]
      }

    };
  },
  computed: {

  },
  methods: {
    getaddpacketstep(){
      console.log()
      let url = encodeURIComponent('messagecity?path=messageBox?id=2')
      addpacketstep(url).then(res=>{
        console.log(res)
      })
    },
    handleChange(value) {

    },
    onCity(values) {
      this.city = values
        .filter((item) => !!item)
        .map((item) => item.name)
        .join('/');
      this.cityIndex = values
        .filter((item) => !!item)
        .map((item) => item.code)
        .join('/');
      console.log('===城市===', this.city);
      this.showArea = false;
      console.log( this.education != '' && this.education != null && this.education != 'undefined',( this.education != '' && this.education != null && this.education != 'undefined'),this.ruleForm.age !== null )
      if(this.education != '' && this.education != null && this.education != 'undefined'){
        this.show = false
      }
    },
    onEdu(value) {
      console.log('===教育===', value);
      this.eduIndex = value.id
      this.education = value.itemText;
      this.showPicker2 = false;
      if(this.ruleForm.age == null || this.ruleForm.age == '' || this.ruleForm.age == 'undefined'){
        console.log(this.city,this.ruleForm.age,'==}|||||||||||||||||||||||||||||||||')
        console.log(this.ruleForm.age != null || this.ruleForm.age != '' || this.ruleForm.age != 'undefined',this.ruleForm.age)
     
          this.show = true
        
     
      }else{
        
        console.log(this.city,this.ruleForm.age,'============================')
        if(this.city == null ){
          
          this.show = true
        }else{
          this.show = false
        }
      }
    },

    getData() {
      var baseUrl = getUrl();
      var phone = ''
      var token = localStorage.getItem('token')
      info({
        phone: this.phoneInfo,
        isSuggest: 3
      }).then(res => {
        console.log(res)
        const userInfo = res.rows[0];
        console.log('userInfo', userInfo);
        // debugger
        // this.ruleForm.userName = userInfo.nickName
        // this.ruleForm.userCardId = userInfo.userCardId
        // this.ruleForm.sex = userInfo.sex
        // this.education = userInfo.education
        this.userCardId = userInfo.userCardId
        this.sex = userInfo.sex
        this.userName = userInfo.nickName
        this.ruleForm.age = userInfo.age
        this.city = userInfo.address
        this.go(this.userCardId.length)
        if(this.city !== null|| this.education !== ''){
          this.show = false
        }

        if (userInfo.education == '0') {
          this.education = '小学及以下'
          this.eduIndex = '0'
        } else if (userInfo.education == '2') {
          this.education = '初中'
          this.eduIndex = '2'
        } else if (userInfo.education == '3') {
          this.education = '高中'
          this.eduIndex = '3'
        } else if (userInfo.education == '4') {
          this.education = '大专'
          this.eduIndex = '4'
        } else if (userInfo.education == '5') {
          this.education = '本科'
          this.eduIndex = '5'
        } else if (userInfo.education == '6') {
          this.education = '硕士'
          this.eduIndex = '6'
        } else if (userInfo.education == '7'){
          this.education = '博士'
          this.eduIndex = '7'
        }else{
          this.education = ''
          this.eduIndex = ''
        }

        this.phone = userInfo.phone
        console.log(this.phone);
        // if (res.data.code == 200) {

        //   // debugger
        //   // localStorage.setItem("token", res.data.data.token);
        //   // this.$router.push('/activity')
        // } else {
        //   // this.$message.error('信息获取失败！');
        // }
      })
    },
    async idcard(rule, value, callback) {
      if (!value) {
        if (rule.field == "id") {
          return callback(new Error("身份证号码不能为空"));
        } else {
          return;
        }
      } else {
        var num = value.charAt(16);
        console.log('数字', num);
        if (num % 2 == 0) {
          console.log(num)
          this.ruleForm.sex = 0
        } else {
          this.ruleForm.sex = 1
        }
        localStorage.setItem('sex', this.ruleForm.sex)
      }
      //setTimeout(() => {
      let regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
      //如果通过该验证，说明身份证格式正确，但准确性还需计算
      if (regIdCard.test(value)) {
        await this.go(value.length);
        // if (value.length == 18) {
        //   var idCardWi = new Array(
        //     7,
        //     9,
        //     10,
        //     5,
        //     8,
        //     4,
        //     2,
        //     1,
        //     6,
        //     3,
        //     7,
        //     9,
        //     10,
        //     5,
        //     8,
        //     4,
        //     2
        //   ); //将前17位加权因子保存在数组里
        //   var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
        //   var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
        //   for (var i = 0; i < 17; i++) {
        //     idCardWiSum += value.substring(i, i + 1) * idCardWi[i];
        //   }
        //   var idCardMod = idCardWiSum % 11; //计算出校验码所在数组的位置
        //   var idCardLast = value.substring(17); //得到最后一位身份证号码
        //   //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
        //   if (idCardMod == 2) {
        //     if (idCardLast == "X" || idCardLast == "x") {
        //       callback();
        //     } else {
        //       callback(new Error("身份证号码错误"));
        //     }
        //   } else {
        //     //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
        //     if (idCardLast == idCardY[idCardMod]) {
        //       callback();
        //     } else {
        //       callback(new Error("身份证号码错误"));
        //     }
        //   }
        // }
      } else {
        callback(new Error("身份证格式不正确"));
      }
      //}, 1000);
    },
    go(val) {
      let iden = this.userCardId;
      console.log('iden',iden);
      let sex = null;
      let birth = null;
      let myDate = new Date();
      let month = myDate.getMonth() + 1;
      let day = myDate.getDate();
      let age = 0;
      if (val === 18) {
        age = myDate.getFullYear() - iden.substring(6, 10) - 1;
        sex = iden.substring(16, 17);
        birth = iden.substring(6, 10) + "-" + iden.substring(10, 12) + "-" + iden.substring(12, 14);
        if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++;

      }
      if (val === 15) {
        age = myDate.getFullYear() - iden.substring(6, 8) - 1901;
        sex = iden.substring(13, 14);
        birth = "19" + iden.substring(6, 8) + "-" + iden.substring(8, 10) + "-" + iden.substring(10, 12);
        if (iden.substring(8, 10) < month || iden.substring(8, 10) == month && iden.substring(10, 12) <= day) age++;
      }

      this.ruleForm.age = age;
    },
    submitForm(formName) {
      if (this.city == "") {
        Toast('请选择您所在的城市！')
      }
      let obj = {}
      obj.education = this.eduIndex
      obj.age = this.ruleForm.age
      obj.address = this.city
      console.log('obj',obj)

     userinfo2(obj).then(res => {
        console.log('userinfo2', res)
        if(res.code == 500){
          Toast(res.msg)
        }else{

          let obj = { buriedPointName: '红包点亮页', section: '4', module: '2', function: '1', redirectPage: '获取红包', orgNo: '' }
              addburyingpoint(obj).then(res => {
                  console.log(res)
              })

        this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.ruleForm));
          var baseUrl = getUrl();
          var token = localStorage.getItem("token");
          params.marriage = 0
          params.occupation = 0
          params.education = this.eduIndex
          params.phone = this.phone
          params.address = this.city
          params.userName = this.userName
          params.sex = this.sex
          params.userCardId = this.userCardId
          params.address = '北京市市辖区朝阳区'
       
          submit(params).then(res => {
            console.log(res)
            Cookies.set("doctorId", res.data.doctorId);
            Cookies.set("token", res.data.token);
            Cookies.set("patientId", res.data.patientId);
            Cookies.set("patientVersion", 1);
            console.log(config.groupId)
            Cookies.set("groupId", config.groupId);
            localStorage.setItem('userinfo', JSON.stringify(res.data))
            let params = { groupId: config.groupId }
            api.getMemoryInfoById(params).then(res => {
              console.log(res)
              if (res.code == 1) {
                console.log(res);
                this.assessCount = res.data.assessCount;
                this.continueTodo = res.data.continueTodo;
                this.nextRoute = res.data.nextRoute;
                if (this.continueTodo != 0) {
                  Cookies.set("patientId", res.data.patientId);
                } else {
                  Cookies.set("masterId", res.data.uuid);
                  // Cookies.set("patientId", '');
                }
                Cookies.set("groupId", res.data.groupId);
              }
            })
            const {
              data
            } = res
            // debugger
            this.data = data.data || {}
            // console.log('data123', res.data.data.url)
            // location.href = (res.data.data.url)
            console.log(res.data.doctorId)

            this.$router.push('/messageBox?id=2')
          })

        } else {
          this.$message.error('请检查填写信息！')
          return false;
        }
      });

    }
      })
      

    },


  },
  mounted() {
    this.getaddpacketstep()
    this.getData()
    if (this.education == '小学及以下') {
      this.eduIndex = '0'
    } else if (this.education == '初中') {
      this.eduIndex = '2'
    } else if (this.education == '高中') {
      this.eduIndex = '3'
    } else if (this.education == '大专') {
      this.eduIndex = '4'
    } else if (this.education == '本科') {
      this.eduIndex = '5'
    } else if (this.education == '硕士') {
      this.eduIndex = '6'
    } else if (this.education == '博士') {
      this.eduIndex = '7'
    }else{
      this.eduIndex = ''
    }
    
  },
};
</script>

<style lang="scss">
.form {
  width: 332px;
  height: 48px;
  display: flex;
  background: #FFFFFF;
  border-radius: 24px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  img {
    width: 17px;
    height: 17px;
    margin-left: 20px;
  }

  .sfz {
    width: 19px;
    height: 14px;
  }
}

.itemform {
  width: 85%;
  // background: #fff;
  margin: auto;
  // margin-top: 10px;
  // padding: 5px 10px;
  // display: flex;
  height: 36px;


  text-align: left;

  input {
    border: none;

  }
}
.one{
  background-color: #f5f7fa;
}
.el-input__inner{
  text-align: right;
}

.el-form {
  display: flex;
  flex-direction: column;
  align-items: center;

}

.xinxi {
  width: 100%;
  height: 100%;
  background-color: #F9F9F9;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.top {
  width: 100%;
}

.bot {
  width: 100%;
  // padding: 20px;
  margin-top: -40px;
  // border-radius: 30px;
  position: relative;
  z-index: 111;
}

.but {
  width: 100%;
  // margin-top: 50px;
  position: absolute;
  bottom: 10px;
  text-align: center;

  img {
    width: 100%;
  }
}

.txk {
  width: 208px;
  height: 157px;
  margin: 20px 0;

  img {
    width: 100%;
  }
}

.el-button--medium {
  width: 70%;
  height: 50px;
  border-radius: 10px;
  font-size: 20px;
}

.text {
  margin-top: 5px;
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #999999;
}

.tipText {
  height: 10px;
  color: gray;
  text-align: center;
  font-size: 20px;
  margin-bottom: 20px;
}
.sex {
  margin-right: 5px;
  display: flex;
  align-items: center;
  justify-content: center;

  img {
    width: 9px;
    height: 16px;
  }
}
.van-cell {
  padding: 6px 10px;
  margin-right: -15px;
}
.van-field::after {
  border-bottom: none;
}
</style>
